package com.soilflow.web.utils.easyexcel;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.soilflow.common.core.domain.AjaxResult;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author steven
 * @date 2022年08月21日 15:42:42
 */
public class EasyExcelUtil {
    public static void exportExcel(HttpServletResponse response, String fileName, List exportData, Class clazz) throws IOException {
        exportExcel(response, fileName, exportData, clazz, "导出成功", 200L);
    }
    /**
     * excel 流导出(需返回前端指定信息时调用该方法)
     *
     * @param response   输出流
     * @param fileName   文件名前缀
     * @param exportData 导出数据
     * @param clazz      Class对象
     * @param resultMsg  返回前端数据（放header里面返回）为空默认导出成功
     * @param code       返回前端状态码：与controller返回状态码一致 全部成功：600 失败：800 为空默认600（放header里面与resultMsg一起返回）
     * @throws IOException 异常
     */
    public static void exportExcel(HttpServletResponse response, String fileName, List exportData, Class clazz, String resultMsg, Long code) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");

            // 设置返回前端信息
            Map<String, Object> result = new HashMap<>();
            result.put("code", code);
            result.put("msg", resultMsg);
            response.setHeader("result", URLEncoder.encode(JSONUtil.toJsonStr(result), "UTF-8"));

            //设置该属性前端可见
            response.setHeader("Access-Control-Expose-Headers", "result,Content-disposition");

            // 使用URLEncoder.encode 防止中文乱码
            String fileNameEncode = URLEncoder.encode(fileName, "UTF-8") + DateUtil.formatDateTime(new Date());
            response.setHeader("Content-disposition", "attachment;filename=" + fileNameEncode + ".xlsx");

            // 设置不关闭流
            EasyExcel.write(response.getOutputStream(), clazz).autoCloseStream(Boolean.FALSE).sheet(fileName).doWrite(exportData);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSON.toJSONString(AjaxResult.error("下载失败")));
        }
    }
}
